//
//  AddressSelectorType.m
//  NZTaxi
//
//  Created by Allan Vergara on 26/09/10.
//  Copyright 2010 List-it. All rights reserved.
//

#import "AddressSelectorType.h"
#import "OrderTaxiTVC.h"
#import "CitySelector.h"
#import "BookingController.h"
#import "Address.h"


@implementation AddressSelectorType

@synthesize personPicker, address;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	
	personPicker =[[ABPeoplePickerNavigationController alloc]init];
	personPicker.peoplePickerDelegate=self;
	address = [[Address alloc] init];
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 3;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"AddressSelectorTypeCell";
	
	OrderTaxiTVC *cell = (OrderTaxiTVC *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
		// Load the top-level objects from the custom cell XIB.
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"OrderTaxiTVC" 
																 owner:self options:nil];
		// Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
		cell = [topLevelObjects objectAtIndex:0];
    }
    
    // Configure the cell...
	NSString *imgSource;
	NSString *menuItemLabel;
	
	switch(indexPath.row) {
		case 0:
			imgSource = [[NSBundle mainBundle] pathForResource:@"home" ofType:@"png"];
			menuItemLabel = @"Home";
			break;
		case 1:
			imgSource = [[NSBundle mainBundle] pathForResource:@"travel_directions" ofType:@"png"];
			menuItemLabel = @"Address";
			break;
		case 2:
			imgSource = [[NSBundle mainBundle] pathForResource:@"phone_book" ofType:@"png"];
			menuItemLabel = @"Contact";
			break;
		/*
		// TODO: recent pick ups
		case 3:
			imgSource = [[NSBundle mainBundle] pathForResource:@"postcard" ofType:@"png"];
			menuItemLabel = @"Recent Pickups";
			break;
		*/
	}
		
	cell.imageView.image = [UIImage imageWithContentsOfFile:imgSource];
	cell.labelMenuItem.text = menuItemLabel;
	
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	NSString *nibName;
	UIViewController *controller;
	NSUserDefaults *preps = [NSUserDefaults standardUserDefaults];
	
	switch (indexPath.row) {
		case 0:						
			if ([[preps stringForKey:C_HOME_CITY] length] == 0) {
				nibName = @"CitySelector";
				controller = [[CitySelector alloc] initWithNibName:nibName bundle:nil];
				((CitySelector *)controller).isHomeAddress = YES;
				
				// Pass the selected object to the new view controller.
				[self.navigationController pushViewController:controller animated:YES];
				[controller release];
			} else { 			
				
				address.houseNumber = [preps stringForKey:C_HOME_HOUSE_NUMBER];
				address.street = [preps stringForKey:C_HOME_STREET];
				address.suburb = [preps stringForKey:C_HOME_SUBURB];
				address.city = [preps stringForKey:C_HOME_CITY];
				
				NSNotification *addressChangeNotification = [NSNotification notificationWithName:C_NOTIFY_ADDRESS_CHANGE 
																						  object:address];
				[[NSNotificationQueue defaultQueue] enqueueNotification:addressChangeNotification
														   postingStyle:NSPostNow 
														   coalesceMask:NSNotificationCoalescingOnName 
															   forModes:nil];
								
				// since we're poping out of here back to the booking controller, let's exit this method
				return;
			}			
			break;
		case 1:
			nibName = @"CitySelector";
			controller = [[CitySelector alloc] initWithNibName:nibName bundle:nil];
			
			// Pass the selected object to the new view controller.
			[self.navigationController pushViewController:controller animated:YES];
			[controller release];			
			break;
		case 2:
			[self presentModalViewController:personPicker animated:YES];			
			break;
		/*
		// TODO: recent pickups
		case 3:			
			break;
		*/
	}		 		
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75;
}

#pragma mark -
#pragma mark Address Book Picker Delegates
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker 
	  shouldContinueAfterSelectingPerson:(ABRecordRef)person {		
	
	//@TODO: check for empty address book 
	
	/* pickup dictionary of address entry from address book */
	ABMultiValueRef homeAddress = ABRecordCopyValue(person, kABPersonAddressProperty);
	CFDictionaryRef addressDict = ABMultiValueCopyValueAtIndex(homeAddress, 0);
	
	/* fill out street and city. iPhone AB don't have house # and suburb */
	address.houseNumber = @"";
	address.suburb = @"";
	address.street = (NSString*)CFDictionaryGetValue(addressDict, kABPersonAddressStreetKey);
	address.city = (NSString*)CFDictionaryGetValue(addressDict, kABPersonAddressCityKey);
	
	/* step 1: close the person picker */
	[self dismissModalViewControllerAnimated:YES];
	
	/* step 2: send notification to the observer controller (which will then pop another view controller) */
	NSNotification *addressChangeNotification = [NSNotification notificationWithName:C_NOTIFY_ADDRESS_CHANGE 
																			  object:address];
	[[NSNotificationQueue defaultQueue] enqueueNotification:addressChangeNotification
											   postingStyle:NSPostNow 
											   coalesceMask:NSNotificationCoalescingOnName 
												   forModes:nil];	
	return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker 
	  shouldContinueAfterSelectingPerson:(ABRecordRef)person 
								property:(ABPropertyID)property 
							  identifier:(ABMultiValueIdentifier)identifier {
	return NO;
}

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
	[self dismissModalViewControllerAnimated:YES];   
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];    
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)dealloc {
	[personPicker release];
	[address release];
    [super dealloc];
}

@end

